<template>
	<div class="video-mark" v-loading="loading.status" :element-loading-text="loading.txt">
		<div class="pointMark_video">
			<div id="newMarkDom">
				<!-- <video
                    id="videoMarkPlayer"
                    ref="videoMarkPlayer"
                    class="video-js vjs-big-play-centered"
                    width="100%"
                    height="100%"
                    oncontextmenu="return false;"
                    disablePictureInPicture
                    controlslist="nodownload">
                </video> -->
				<dplayer key="dplayer" ref="dplayer" :playParam.sync="playerOptions" :pointData="pointData">
				</dplayer>
			</div>
		</div>
		<div class="publishFrom">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="标注信息" prop="comment">
					<el-input v-model.trim="ruleForm.comment" maxlength="15" placeholder="描述标注信息，不超过15个字"></el-input>
				</el-form-item>
				<div class="publishFrom_if clear">
					<el-form-item label="打点时间" prop="dottingTime" class="publishFrom_if_l fl">
						<span>
							<el-time-picker v-model="ruleForm.dottingTime" :clearable="false" :editable="false"
								value-format="HH:mm:ss" :picker-options="{
									format: 'HH:mm:ss',
									selectableRange: timeMax
								}" placeholder="任意时间点">
							</el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlayTime()"></i>
					</el-form-item>
					<!--  -->
					<div class="publishFrom_if_r fr">
						<el-form-item class="buttonCSS" label-width="0" prop="thumbnail">
							<!-- <el-checkbox v-model="ruleForm.thumbnail">视频缩略图</el-checkbox> -->
							<!-- <el-button @click="resetForm('ruleForm')" type="primary" plain>取消</el-button> -->
							<el-button type="primary" @click="submitForm('ruleForm')">生成知识点</el-button>
						</el-form-item>
					</div>
				</div>

			</el-form>
		</div>
		<div class="publishFrom_table">
			<template>
				<el-table border :data="pointData" style="width: 100%">
					<el-table-column prop="text" label="标注信息">
					</el-table-column>
					<el-table-column prop="newTime" label="打点时间">
					</el-table-column>
					<el-table-column label="操作" align="center" width="160">
						<template slot-scope="scope">
							<el-button @click="deleteVideoPoint(scope.row)" type="text" class="delete-button" size="small">删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>

		</div>
	</div>

</template>
<script>
// import 'videojs-flash';
// import SWF_URL from 'videojs-swf/dist/video-js.swf';
import dplayer from '@/components/public/dplayer.vue';

export default {
	components: {
		dplayer,
	},
	props: ['compParam', 'activeIndex'],
	name: '',

	data() {
		return {
			thisIndex: '2',
			loading: {
				status: false,
				txt: '获取数据...'
			},
			timeMax: '00:00:00',
			checked: true,
			ruleForm: {
				videoName: '', //视频名称
				dottingTime: '00:00:00', //打点时间
				thumbnail: true, //缩略图

			},
			rules: {
				comment: [
					{ required: true, message: '请输入标注信息', trigger: 'blur' },
					{ min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
				],
				dottingTime: [
					{ required: true, message: '请输入打点时间', trigger: 'blur' },
				]
			},
			// player: null, // 播放器
			// playerOptions : {
			// 	  loop: false,
			//       height: '360',
			//       sources: [{
			//         type: "rtmp/mp4",
			//         src: "blala"
			//       }],
			//      techOrder: ['flash'],
			//      flash: {swf: SWF_URL },
			//       autoplay: false,
			//       controls: true,
			//       poster: "",
			// 	  controlBar: {
			//           timeDivider: true,
			//           durationDisplay: true,
			//           remainingTimeDisplay: false,
			//           fullscreenToggle: true  //全屏按钮
			//         }
			// },
			// playerOptions: {
			// 	loop: false, // true -- 视频一结束就重新开始
			// 	controls: true,
			// 	fluid: false,
			// 	autoplay: false, // true--浏览器准备好时开始回放
			// 	height: '360',
			// 	poster: "", // 封面地址
			// 	language: 'zh-CN',
			// 	// techOrder: ['flash'],
			// 	sources: [{
			// 		type: "application/x-mpegURL",
			// 		src: this.compParam.play_url // 视频播放路径
			// 	}],
			// 	controlBar: {
			// 		children: [
			// 			{ name: 'playToggle' }, // 播放按钮
			// 			{ name: 'currentTimeDisplay' }, // 当前已播放时间
			// 			{ name: 'progressControl' }, // 播放进度条
			// 			{ name: 'durationDisplay' }, // 总时间
			// 			{
			// 				name: 'volumePanel', // 音量控制
			// 				inline: false, // 不使用水平方式
			// 			},
			// 			{ name: 'FullscreenToggle' } // 全屏
			// 		]
			// 	},
			// },
			playerOptions: {
				play_url: this.compParam.play_url,
			},
			pointData: [],
		}
	},
	mounted() {
		// this.initPlay();
		this.initFunc();
	},
	beforeDestroy() {
		this.player && this.player.dispose();
	},
	methods: {
		/**
		 * 改变进度条
		 */
		// onSlicePlay() {
		// 	this.debounce(() => {
		// 		var normal_currentTime = this.player.currentTime();
		// 		var unnormal_currentTime = this.player.currentTime();
		// 		if (normal_currentTime.toString() == unnormal_currentTime.toString()) {
		// 			this.player.pause();
		// 			this.player.play();
		// 		}
		// 	}, 100);
		// },
		/**
		 * 延迟处理
		 */
		debounce(func, wait, immediate) {
			let timeout, args, context, timestamp, result;
			const later = function () {
				// 据上一次触发时间间隔
				const last = +new Date() - timestamp;

				// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
				if (last < wait && last > 0) {
					timeout = setTimeout(later, wait - last);
				} else {
					timeout = null;
					// 如果设定为immediate===true，因为开始已经调用过了此处无需调用
					if (!immediate) {
						result = func.apply(context, args);
						if (!timeout) context = args = null;
					}
				}
			};
			return function (...args) {
				context = this;
				timestamp = +new Date();
				const callNow = immediate && !timeout;
				// 如果延时不存在，重新设定延时
				if (!timeout) timeout = setTimeout(later, wait);
				if (callNow) {
					result = func.apply(context, args);
					context = args = null;
				}

				return result;
			};
		},
		/**
		 * 播放器初始
		 */
		// initPlay() {
		// 	let self = this;
		// 	this.player && this.player.dispose();
		// 	let videoMarkPlayer = document.getElementById('newMarkDom');
		// 	videoMarkPlayer.innerHTML = '<video id="videoMarkPlayer" class="video-js vjs-big-play-centered" width="100%" height="100%" oncontextmenu="return false;" disablePictureInPicture controlslist="nodownload"> </video>'
		// 	this.player = this.$videojs('videoMarkPlayer', this.playerOptions, function onPlayerReady() { })

		// 	// 初始音量50%
		// 	this.player.volume(0.5)

		// 	this.player.on('play', function () {
		// 		self.onSlicePlay();
		// 	})
		// },
		initFunc() {
			// this.player.src({ type : "rtmp/mp4", src : this.compParam.play_url }) ;
			this.getPointMark();
		},
		//视频信息
		getPointMark() {
			//this.pointData = [];
			this.loading.status = true;
			let success = (data => {
				this.loading.status = false;
				let result = data.data;
				this.timeMax = '00:00:00 - ' + result.length;
				this.pointData = result.point
				this.pointData = JSON.parse(JSON.stringify(this.pointData).replace(/video_time/g, 'time').replace(/comment/g, 'text'));
				// console.log('241', this.pointData)

				for (let i = this.pointData.length - 1; i >= 0; i--) {
					var newTime = formatSeconds(this.pointData[i].time);
					this.pointData[i]['newTime'] = newTime.hour + ':' + newTime.minute + ':' + newTime.second

					// console.log('1', pointData)

				}
				// console.log(this.pointData);
				// this.pointData[i].video_time_num = this.pointData[i].video_time;
				// 	this.pointData[i].video_time = newTime.hour + ':' + newTime.minute + ':' + newTime.second
				// }
				// this.timeMax = '00:00:00 - ' + result.length;
				// this.resolveMark();

				// for (var i = this.pointData.length - 1; i >= 0; i--) {
				// 	var newTime = formatSeconds(this.pointData[i].video_time);
				// 	this.pointData[i].video_time_num = this.pointData[i].video_time;
				// 	this.pointData[i].video_time = newTime.hour + ':' + newTime.minute + ':' + newTime.second
				// }
				// this.timeMax = '00:00:00 - ' + result.length;
				// this.resolveMark();
			});
			let fail = (data => {
				this.loading.status = false;
				this.$message.error(data.msg)
			})
			this.$ajax.get('api/video/video_point_list', { params: { videoid: this.compParam.id }, func: { success: success } })
		},
		getVideoPlayTime() {
			// var nowTime = formatSeconds(this.player.currentTime());
			this.$refs.dplayer.player.pause();
			let nowTime = formatSeconds(this.$refs.dplayer._data.videoCurrentTime)
			// console.log(nowTime)
			this.ruleForm.dottingTime = nowTime.hour + ':' + nowTime.minute + ':' + nowTime.second
		},
		savePoint() {
			var videotime = this.ruleForm.dottingTime.split(":"); // 时间字符分割 
			var videotimeSeconds = parseInt(videotime[0] * 3600) + parseInt(videotime[1] * 60) + parseInt(videotime[2]); // 时间转成秒数
			var params = {
				videoid: this.compParam.id,
				comment: this.ruleForm.comment,
				videotime: videotimeSeconds,
				thumbnail: this.ruleForm.thumbnail ? 1 : 0
			}

			let success = (data => {
				this.$message.success(data.msg);
				this.getPointMark();
				this.$forceUpdate();
				this.resetForm('ruleForm');
			});
			this.$ajax.post('api/video/video_point', params, { func: { success: success } })
		},
		deleteVideoPoint(obj) {
			let yes = (data => {
				let success = (data => {
					this.getPointMark();
					this.$message.success(data.msg)
				})
				this.$ajax.delete('api/video/video_point', { params: { id: obj.id }, func: { success: success } })
			})
			let cancel = (data => { })
			this.e_confirm({ yes: yes, cancel: cancel, txt: '确定将 ' + obj.comment + ' 删除吗？' });
		},
		/**
		 * 先删除所有打点，再添加
		 */
		resolveMark() {
			//
			var dotting_time_element = this.player.controlBar.progressControl.el_.children[0].getElementsByClassName('dotting_time');
			if (dotting_time_element.length > 0) {
				for (var i = dotting_time_element.length - 1; i >= 0; i--) {
					this.player.controlBar.progressControl.el_.children[0].removeChild(dotting_time_element[i]);
				}
			}

			if (this.pointData.length > 0) {
				var newTime = this.compParam.length.split(':');
				var total_time_num = parseInt(newTime[0]) * 3600 + parseInt(newTime[1]) * 60 + parseInt(newTime[2]);
				for (var i = 0; i < this.pointData.length; i++) {
					var left = this.pointData[i].video_time_num / total_time_num * 100;
					var image = this.pointData[i].picture != '' ? `<img src="${this.BASE_URL}${this.pointData[i].picture}" >` : '';
					var html = `<div class="dotting_time"  
										style="background:#54b554;
										left: ${left}%;
										width:5px;height:100%;
										position:absolute;z-Index:55;"
										 current_time="">
										<div class="low_source">
											<p class="low_h">${this.pointData[i].comment}</p>
											${image}
											<p class="low_h">${this.pointData[i].video_time}</p>
										</div>
									</div>`
					this.player.controlBar.progressControl.el_.children[0].insertAdjacentHTML('beforeend', html)
				}
			}
		},
		//视频
		// listen event
		// onPlayerPlay(player) {
		// 	//渲染打点
		// 	this.resolveMark();
		// },
		onPlayerPause(player) {
		},
		handleSelect(key, keyPath) {
		},
		//表单验证
		submitForm(formName) {
			if (this.ruleForm.dottingTime === '00:00:00') {
				this.$message.error('请选择开始时间');
				return false;
			}

			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.savePoint();
				} else {
					return false;
				}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
	}
}
</script>

<style  lang="scss">
.video-mark {
	.publishFrom {
		margin-top: 30px;
	}
}

#newMarkDom {
	height: 400px
}

.publishFrom_if_l {
	>span {
		color: #606266;
		margin-left: 25px;

		.el-date-editor {
			margin-left: 15px;
		}
	}

	.el-icon-location {
		font-size: 20px;
		color: #409EFF;
		padding: 10px;
		background: #E8F2FF;
		border-radius: 3px;
		vertical-align: middle;
		cursor: pointer;
	}

	.el-date-editor {
		width: 180px;
	}
}

.pageBox {
	.el-pagination {
		text-align: left;
	}


	.el-pagination__sizes {
		display: none !important;
	}

	.el-pager {
		li {
			color: #6A87AC;
			padding: 0;
			min-width: 30px;
		}

		.active {
			color: #fff;
			background: #409EFF;
		}
	}

	.el-pagination__total,
	.el-pagination__jump {
		color: #6A87AC;
	}

	.el-input__inner {
		border: 1px solid #D5EAFB;
		border-radius: 0;
	}
}

.dotting_time {
	&:hover {
		.low_source {
			opacity: 1;
			visibility: visible;
		}
	}
}

.low_source {
	position: absolute;
	background: #fff;
	width: 200px;
	bottom: 20px;
	left: -100px;
	padding: 15px;
	border-radius: 4px;
	transition: .5s;
	opacity: 0;
	visibility: hidden;

	>p {
		color: #000;
		font-size: 12px;
		text-align: left;
		margin: 0;
	}

	>img {
		width: 100%;
		margin: 10px;
	}

	&:after {
		content: '';
		width: 0;
		height: 0;
		border-width: 12px 9px 0;
		border-style: solid;
		border-color: #fff transparent transparent;
		position: absolute;
		bottom: -12px;
		left: 50%;
		margin-left: -6px;
	}
}
</style>
